package fastwave.common.auth.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import fastwave.common.auth.constant.CommonConstants;
import fastwave.common.auth.constant.SecurityConstants;
import fastwave.common.auth.entity.AuthUser;
import fastwave.common.auth.entity.UserInfo;
import fastwave.common.auth.sys.entity.SysUser;
import fastwave.common.auth.sys.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 使用接口方式，实现用户信息的获取
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MyUserDetailsService implements UserDetailsService {
    private final SysUserService userService;
    private final PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户名：{}", username);

        /*
        // 根据用户名查找用户信息
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("admin1");
        // 判断用户状态
        User user = new User(username, passwordEncoder.encode("123"), true, true, true, true, authorities);
        return user;
         */

        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        UserInfo userInfo = userService.getUserInfo(user);

        UserDetails userDetails = getUserDetails(userInfo);
        return userDetails;
    }

    /**
     * 构建userdetails
     * @param userInfo 用户信息
     * @return
     */
    private UserDetails getUserDetails(UserInfo userInfo) {
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        Set<String> dbAuthSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(userInfo.getRoles())) {
            // 获取角色
            Arrays.stream(userInfo.getRoles()).forEach(role -> dbAuthSet.add(SecurityConstants.ROLE + role));
            // 获取资源
            dbAuthSet.addAll(Arrays.asList(userInfo.getPermissions()));
        }
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(dbAuthSet.toArray(new String[0]));
        SysUser user = userInfo.getSysUser();

        // 构造security用户
        return new AuthUser(user.getUserId(), user.getDeptId(), user.getUsername(), user.getPassword(),
                StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), true, true, true, authorities);
    }
}
